package top.fangw.gateway.filter;

import cn.hutool.core.util.StrUtil;
import com.nimbusds.jose.JWSObject;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import top.fangw.common.oauth.util.RSAUtils;

import java.net.URLEncoder;
import java.util.Map;

/**
 * @description: 安全拦截全局过滤器
 * @author: fgw
 * @createDate: 2023/11/19
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class SecurityGlobalFilter implements GlobalFilter, Ordered {
    @SneakyThrows
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String token = request.getHeaders().getFirst("Authorization");
        String tenantId = request.getHeaders().getFirst("tenantId");
        ServerHttpRequest.Builder mutate = exchange.getRequest().mutate();
        if(StrUtil.isNotBlank(token) && !token.startsWith("Basic")){
            token = StrUtil.replaceIgnoreCase(token, "Bearer ", Strings.EMPTY);
            Map<String, Object> jsonObject = JWSObject.parse(token).getPayload().toJSONObject();
            String external = jsonObject.get("external").toString();
            String s = RSAUtils.decryptByPubKey(external, RSAUtils.publicKeyBase64Default);
            mutate.header("payload", URLEncoder.encode(s, "UTF-8"));
        }
        if(StrUtil.isNotBlank(tenantId)){
            mutate.header("tenantId", tenantId);
        }

        exchange = exchange.mutate().request(mutate.build()).build();
       return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
